package top.lshaci.learning.excel;

import cn.hutool.core.io.file.FileNameUtil;
import com.aspose.words.Document;
import com.aspose.words.License;
import com.aspose.words.SaveFormat;
import lombok.extern.slf4j.Slf4j;

import java.io.FileOutputStream;
import java.io.InputStream;
import java.util.Optional;

/**
 * Word2Pdf
 *
 * @author liangxu
 */
@Slf4j
public class Word2Pdf {

    public static void convert(String wordFilePath, String pdfFilePath) throws Exception {
        getLicense();
        Document document = new Document(wordFilePath);
        FileOutputStream pdfFos = new FileOutputStream(Optional.ofNullable(pdfFilePath).orElseGet(() -> Word2Pdf.pdfFilePath(wordFilePath)));
        document.save(pdfFos, SaveFormat.PDF);
        pdfFos.flush();
        pdfFos.close();
    }

    private static String pdfFilePath(String wordFilePath) {
        return FileNameUtil.getPrefix(wordFilePath) + ".pdf";
    }

    private static void getLicense() {
        String licenseFilePath = "word-license.xml";
        try {
            InputStream is = Word2Pdf.class.getClassLoader().getResourceAsStream(licenseFilePath);
            License license = new License();
            license.setLicense(is);
        } catch (Exception e) {
            log.error("License verify failed!", e);
        }
    }

}
